package jjn.daily;

import java.util.*;

/**
 * @author Jiang Jining
 * @since 2023-08-27 12:56
 */
public class LeetCode56 {
    public int[][] merge(int[][] intervals) {
        Arrays.sort(intervals, Comparator.comparingInt(i -> i[0]));
        Deque<int[]> result = new ArrayDeque<>();
        for (int[] interval : intervals) {
            int left = interval[0], right = interval[1];
            if (result.isEmpty() || result.peekLast()[1] < left) {
                result.offer(new int[]{left, right});
                continue;
            }
            result.peekLast()[1] = Math.max(right, result.peekLast()[1]);
        }
        return result.toArray(new int[result.size()][]);
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int m = scanner.nextInt();
        int n = scanner.nextInt();
        int[][] intervals = new int[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                intervals[i][j] = scanner.nextInt();
            }
        }
        int[][] merged = new LeetCode56().merge(intervals);
        String joined = String.join(",", Arrays.deepToString(merged));
        System.out.println(joined);
    }
}
